package com.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.config.StpInterfaceImpl;
import com.dto.UserLoginDto;
import com.dto.UserSaveDto;
import com.exceptions.DataBaseException;
import com.mysql.cj.x.protobuf.MysqlxCursor;
import com.po.User;
import com.result.Result;
import com.service.UserService;
import com.vo.UserLoginVo;
import com.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.time.LocalDateTime;

@RestController
@RequestMapping("/user/")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    /**
     * 用户注册
     * @param userSaveDto
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody UserSaveDto userSaveDto){
        log.info("创建用户：{}",userSaveDto);
        User user = new User();
        user.setStatus(1L);
        BeanUtil.copyProperties(userSaveDto,user);
        user.setCreateTime(LocalDateTime.now());
        try {
            userService.save(user);
        } catch (Exception e) {
            throw new DataBaseException("已有用户注册！请更换用户名！");
        }
        return Result.success();
    }

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto){
        log.info("用户登录：{}",userLoginDto);
        UserLoginVo userLoginVO = userService.login(userLoginDto);
        return Result.success(userLoginVO);
    }

    /**
     * 用户上传更改头像
     * @param image
     * @return
     */
    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam MultipartFile image){
        userService.uploadAvatar(image);
        return Result.success();
    }

    /**
     * 用户更改用户名
     * @param name
     * @return
     */
    @PostMapping("/changeName")
    public Result changeName(@RequestParam String name){
        log.info("user:{}更改用户名", StpUtil.getLoginIdAsLong());
        userService.changeName(name);
        return Result.success();
    }

    /**
     * 根据用户id查询用户
     * @param id
     * @return
     */
    @GetMapping("get")
    public Result<UserVo> get(@RequestParam Long id){
        log.info("根据用户id查询用户:{}",id);
        User user = userService.getById(id);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user,userVo);
        return Result.success(userVo);
    }

    /**
     * 个人用户升级为商家
     * @param id
     * @return
     */
    @PutMapping("up")
    public Result up(@RequestParam Long id){
        LambdaUpdateWrapper<User> in = new LambdaUpdateWrapper<User>()
                .set(User::getIsAdmin, 1)
                .in(User::getId, id);
        userService.update(null,in);
        return Result.success();
    }
}
